import time
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse

class RequestLoggingMiddleware(MiddlewareMixin):
    # 中间件会在路由到达视图函数前/视图函数后 自动分别执行 process_request/process_response
    def process_request(self, request):
        print("process_request--------------------")
        request.start_time = time.time()
        """
        在这里就可以查询用户的角色菜单，通过判断，进行权限拦截
        if 2==2:
           return HttpResponse("服务被拒绝！")
        """


    def process_response(self, request, response):
        print("process_response---------------------------")
        duration = time.time() - request.start_time
        log_data = {
            'path': request.path,
            'method': request.method,
            'params': request.GET.dict(),
            'duration': duration,
        }
        print(log_data)  # 或者将日志保存到数据库
        return response
